/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.services.gl;

/**
 *
 * @author jay
 */

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.model.SelectItem;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import src.HibernateUtil;
import src.domain.gl.Jv;
import src.services.CRUEDService;

public class JvModel implements java.io.Serializable {
    
    private CRUEDService service;
    
    public JvModel() {
        service = new CRUEDService();
    }
    
    public List<Jv> findAll(Map<String, String> filters) {
        return (List<Jv>) service.findAll("Jv", filters);
    }

    public List<SelectItem> listAll() {
        return service.listAll("Jv", "jvId", "jvNo");
    }
    
    public Jv getByAccount(String value) {
        Map<String, String> where = new HashMap<>();
        where.put("jv.jvNo", value);
        return (Jv) service.getObjectSQL("from Jv jv", where);
    }
    
    public boolean saveData(Jv data) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        org.hibernate.Transaction tx = session.beginTransaction();
        boolean success;
        
        try {
            session.saveOrUpdate(data);
            
            if (data.getPosted()) {
                session.flush();
                Query q = session.createSQLQuery(" { call jv_actions.posting_jv(?, ?, ?) }");
                q.setInteger(0,data.getJvId());  
                q.setDate(1,data.getJvDate());  
                q.setInteger(2,data.getBranchId());  
                q.executeUpdate();
            }
            tx.commit();
            success = true;  
            
        } catch (RuntimeException e) {
            
            if (tx != null && tx.isActive()) {
                try {
                    tx.rollback();
                } catch (HibernateException e1) {}
            }
            success = false;  
            Logger.getLogger(JvModel.class.getName()).log(Level.SEVERE, null, e);
        }
        
        return success;
    }
    
    public boolean deleteData(Jv data) {
        return service.deleteData(data);
    }
}
